<template>
 <div class="cart">

  <!-- 商品为空时显示空提示, 购物车长度为0时显示提示 -->
  <van-empty
      image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
      image-size="80"
      description="购物车为空，请选购商品"
      v-if="cart.length === 0" 
    />
    <!-- 有商品时则显示商品列表 -->
     <template v-else>
      <van-swipe-cell v-for="goods in cart" :key="goods.id">
        <van-card
          :price="goods.price"
          :title="goods.title"
          class="goods-card"
          @click-thumb="$router.push('/detail?id=' + goods.id)"
        >
        <!-- 自定义插槽，定义数量加减组件 -->
        <template #num>
          <van-stepper 
            :modelValue="goods.amount" 
            theme="round" 
            button-size="22"
            @change="handleAmountChange($event, goods.id)"
          />
        </template>
        <!-- 自定义插槽，定义复选框组件 -->
         <template #thumb>
          <van-checkbox 
            :modelValue="goods.checked" 
            checked-color="#ee0a24" 
            @click.stop="toggle(goods.id)"
          />
          <div class="van-image" style="width: 88px; height: 100%">
            <img :src="goods.image" class="van-image__img" style="object-fit: cover;">
          </div>
         </template>
        </van-card>
        <template #right>
          <van-button 
            square text="删除" 
            type="danger" 
            class="delete-button" 
            @click="removeCart(goods.id)"
          />
        </template>
      </van-swipe-cell>

           <!-- 提交订单 -->
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="">
          <van-checkbox 
            :modelValue="isAllChecked"
            @click="checkAll(!isAllChecked)"
          >全选</van-checkbox>
          <template #tip>
            你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
          </template>
        </van-submit-bar>
     </template>
 </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
export default {
 name: 'Cart',
 data() {
  return {
    
  }
 },
//  印设计算属性中的方法
 computed: {
  ...mapGetters('shoppingCart', ['cart', 'totalPrice', 'isAllChecked',])
 },
 methods: {
  ...mapMutations('shoppingCart', ['toggle', 'removeCart', 'modifyAmount', 'checkAll']),

  // 购物车中商品数量变化
  handleAmountChange(amount, id){
    console.log(amount, id)
    // 调用mutation方法，将修改后的数量保存到store仓库中
    this.modifyAmount({amount, id})
  }
 }
}
</script>

<style lang="scss" scoped>
.cart{
  padding-bottom: 90px;
}
 .goods-card {
    margin: 0;
    background-color: #fff;
  }
  .delete-button {
    height: 100%;
  }
  :deep(.van-card__thumb){
    width: 120px;
    display: flex;
    justify-content: space-around;
  }
  .van-submit-bar{
    bottom: 50px;
  }
</style>
